package com.snmp.smn.monitors;

import java.net.Socket;

import com.snmp.smn.beans.Agent;
import com.snmp.smn.beans.Device;
import com.snmp.smn.db.DBHelper;
import com.snmp.smn.pdu.PDUFactory;

public abstract class DeviceMonitor {
	
	protected Device device;

	public abstract void checkDevice() throws Exception;
	
	protected void updateSuccessfulCheck() throws Exception {
		DBHelper.insertSuccessfulCheck(device.getDeviceId());
		
		DBHelper.updateSuccessfulDeviceStatus(device.getDeviceId());
	}
	
	protected void updateFailedCheck() throws Exception {
		DBHelper.insertFailedCheck(device.getDeviceId());
		
		DBHelper.updateFailedDeviceStatus(device.getDeviceId());
	}
	
	protected void restartDevice() throws Exception {
		Agent agent = DBHelper.getAgentByIP(device.getDeviceIP());
		
		sendCommand(agent.getAgentIP(), agent.getAgentPort(), device.getCommand());
	}

	private void sendCommand(String agentIP, int agentPort, String command) throws Exception {
		Socket socket = new Socket(agentIP, agentPort);
		socket.getOutputStream().write(PDUFactory.createSetRequestPDU(command));
		socket.close();
	}	
}
